package com.example.pclimb.viewmodel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.pclimb.model.ClimbRequest;
import com.example.pclimb.model.User;
import com.example.pclimb.repository.ClimbRequestRepository;
import com.example.pclimb.repository.UserRepository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 陪爬申请视图模型，负责处理陪爬申请相关的UI数据
 */
public class ClimbRequestViewModel extends AndroidViewModel {
    private static final String TAG = "ClimbRequestViewModel";
    private ClimbRequestRepository repository;
    private LiveData<List<ClimbRequest>> pendingRequests;
    private LiveData<List<ClimbRequest>> matchedRequests;
    private LiveData<List<ClimbRequest>> awaitingPaymentRequests;
    private LiveData<List<ClimbRequest>> completedRequests;
    private LiveData<List<ClimbRequest>> cancelledRequests;
    private MutableLiveData<ClimbRequest> selectedRequest = new MutableLiveData<>();

    public ClimbRequestViewModel(@NonNull Application application) {
        super(application);
        repository = new ClimbRequestRepository(application);
        pendingRequests = repository.getPendingRequests();
        matchedRequests = repository.getMatchedRequests();
        awaitingPaymentRequests = repository.getAwaitingPaymentRequests();
        completedRequests = repository.getCompletedRequests();
        cancelledRequests = repository.getCancelledRequests();
    }

    public void insert(ClimbRequest climbRequest, UserRepository.Callback<Long> callback) {
        repository.insert(climbRequest, callback);
    }

    public void update(ClimbRequest climbRequest) {
        repository.update(climbRequest);
    }

    public void delete(ClimbRequest climbRequest) {
        repository.delete(climbRequest);
    }

    public LiveData<List<ClimbRequest>> getPendingRequests() {
        return pendingRequests;
    }

    public LiveData<List<ClimbRequest>> getMatchedRequests() {
        return matchedRequests;
    }
    
    public LiveData<List<ClimbRequest>> getAwaitingPaymentRequests() {
        return awaitingPaymentRequests;
    }

    public LiveData<List<ClimbRequest>> getCompletedRequests() {
        return completedRequests;
    }
    
    public LiveData<List<ClimbRequest>> getCancelledRequests() {
        return cancelledRequests;
    }

    public LiveData<List<ClimbRequest>> getUserRequests(int userId) {
        return repository.getUserRequests(userId);
    }

    public LiveData<List<ClimbRequest>> getGuideRequests(int guideId) {
        return repository.getGuideRequests(guideId);
    }

    public LiveData<ClimbRequest> getClimbRequestById(int requestId) {
        return repository.getClimbRequestById(requestId);
    }

    /**
     * 根据ID获取陪爬申请
     * @param requestId 申请ID
     * @return 申请数据
     */
    public LiveData<ClimbRequest> getRequestById(int requestId) {
        return repository.getClimbRequestById(requestId);
    }

    /**
     * 根据ID获取陪爬申请（使用long类型参数）
     * @param requestId 申请ID
     * @return 申请数据
     */
    public LiveData<ClimbRequest> getRequestById(long requestId) {
        Log.d(TAG, "使用long类型ID获取请求: " + requestId);
        return repository.getClimbRequestById((int)requestId);
    }

    /**
     * 更新陪爬申请
     * @param request 需要更新的申请
     */
    public void updateRequest(ClimbRequest request) {
        repository.update(request);
    }

    public void matchRequest(int requestId, int guideId) {
        repository.matchRequest(requestId, guideId);
    }
    
    public void setAwaitingPayment(int requestId) {
        repository.setAwaitingPayment(requestId);
    }

    public void completeRequest(int requestId) {
        repository.completeRequest(requestId);
    }

    public void cancelRequest(int requestId) {
        repository.cancelRequest(requestId);
    }

    public void setPrice(int requestId, double price) {
        repository.setPrice(requestId, price);
    }

    public void markAsPaid(int requestId) {
        repository.markAsPaid(requestId);
    }

    public LiveData<List<ClimbRequest>> getRequestsByDateRange(Date startDate, Date endDate) {
        return repository.getRequestsByDateRange(startDate, endDate);
    }

    public LiveData<List<ClimbRequest>> getRequestsByLocation(String location) {
        return repository.getRequestsByLocation(location);
    }

    public void setSelectedRequest(ClimbRequest request) {
        selectedRequest.setValue(request);
    }

    public LiveData<ClimbRequest> getSelectedRequest() {
        return selectedRequest;
    }

    // 推荐匹配算法
    public LiveData<List<User>> recommendGuidesForRequest(ClimbRequest request, List<User> availableGuides) {
        MutableLiveData<List<User>> recommendedGuides = new MutableLiveData<>();
        List<User> recommendations = new ArrayList<>();
        
        // 简单实现：根据评分高低排序
        availableGuides.sort((g1, g2) -> Float.compare(g2.getRating(), g1.getRating()));
        
        // 取前5名或者所有可用导游
        int count = Math.min(5, availableGuides.size());
        for (int i = 0; i < count; i++) {
            recommendations.add(availableGuides.get(i));
        }
        
        recommendedGuides.setValue(recommendations);
        return recommendedGuides;
    }

    /**
     * 刷新待匹配的申请
     */
    public void refreshPendingRequests() {
        pendingRequests = repository.getPendingRequests();
    }

    /**
     * 刷新已匹配的申请
     */
    public void refreshMatchedRequests() {
        matchedRequests = repository.getMatchedRequests();
    }
    
    /**
     * 刷新待支付的申请
     */
    public void refreshAwaitingPaymentRequests() {
        awaitingPaymentRequests = repository.getAwaitingPaymentRequests();
    }

    /**
     * 刷新已完成的申请
     */
    public void refreshCompletedRequests() {
        completedRequests = repository.getCompletedRequests();
    }
    
    /**
     * 刷新已取消的申请
     */
    public void refreshCancelledRequests() {
        cancelledRequests = repository.getCancelledRequests();
    }
}